package com.xieyong.mywebsite.service.Impl;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xieyong.mywebsite.mapper.BlogMapper;
import com.xieyong.mywebsite.model.entity.Blog;
import com.xieyong.mywebsite.service.BlogService;
import com.xieyong.mywebsite.service.FileService;
import com.xieyong.mywebsite.util.TokenUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {

    @Resource
    private BlogMapper blogMapper;
    @Autowired
    private FileService fileService;


    @Override
    public Blog getBlogById(Integer id) {
        return blogMapper.selectBlogById(id);
    }

    @Override
    public List<Blog> getAllBlog() {
        return blogMapper.selectAllBlog();
    }

    @Override
    public PageInfo<Blog> getBlogPage(Integer pageNum, Integer pageSize, Blog blog, Date startTime, Date endTime) {
        PageHelper.startPage(pageNum, pageSize);
        List<Blog> blogs = blogMapper.selectBlogByCondition(blog.getCreateId(), blog.getTitle(), blog.getContent(), startTime, endTime);
        return PageInfo.of(blogs);
    }

    @Override
    public void insertBlog(Blog blog) {
        blogMapper.insertBlog(blog);
    }

    @Override
    public void updateBlog(Blog blog) {
//        更新前删除原来的图片
        fileService.removeFile(blogMapper.selectBlogById(blog.getId()).getImg());
        blogMapper.updateBlog(blog);
    }

    @Override
    public void deleteBlog(Integer id) {
        blogMapper.deleteBlog(DateUtil.date(), TokenUtil.getCurrentUser().getId(),id);
    }

    @Override
    public void deleteBlogs(List<Integer> ids) {
        for (Integer id : ids) {
            blogMapper.deleteBlog(DateUtil.date(), TokenUtil.getCurrentUser().getId(),id);
        }
    }
}
